#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

namespace SocketModule
{
    using namespace LogModule;
    const static int defaultfd = -1;
    const static int defaultbacklog = 16;

    class Socket//基类socket，大部分方法都是纯虚
    {
    public:
        virtual ~Socket(){}
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(int backlog) = 0;
        virtual std::shared_ptr<Socket> Accept(InetAddr* client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string* out) = 0;
        virtual int Send(const std::string& message) = 0;
        virtual int Connect(const std::string& server_ip,uint16_t port) = 0;
    public:
        void BuildTcpSocketMethod(uint16_t port,int backlog = defaultbacklog)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(backlog);
        }

        void BuildTcpClientSocketMethod()
        {
            SocketOrDie();
        }
    };

    class TcpSocket:public Socket
    {
    public:
        TcpSocket():_sockfd(defaultfd)
        {}
        TcpSocket(int fd):_sockfd(fd)
        {}
        ~TcpSocket(){}

        void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET,SOCK_STREAM,0);//::表面用命名空间外的socket
            if(_sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "socket error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "socket success";
        }

        void BindOrDie(uint16_t port) override
        {
            InetAddr addr(port);
            int n = ::bind(_sockfd,addr.NetAddrPtr(),addr.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success";
        }

        void ListenOrDie(int backlog) override
        {
            int n = ::listen(_sockfd,backlog);
            if(n < 0)
            {
                LOG(LogLevel::FATAL) << "listen error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success";
        }
        
        std::shared_ptr<Socket> Accept(InetAddr* client) override
        {
            //client是输出型参数
            //为什么是输出型？因为socket套接字包含Accept函数
            //该函数必须获得客户端信息，但该Socket类又没有该成员
            //只能在TcpServer中记录
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = ::accept(_sockfd,CONV(peer),&len);
            if(fd < 0)
            {
                LOG(LogLevel::WARNING) << "accept warning ...";
                return nullptr; // TODO
            }
            client->SetInetAddr(peer);
            return std::make_shared<TcpSocket>(fd);
            //由于我们封装了socket类，因此都用socket来封装使用最好
        }

        int Recv(std::string *out) override
        {
            //每次读的字符都要加到外部的string缓冲区中
            char buffer[4096*2];
            ssize_t n = ::recv(_sockfd,buffer,sizeof(buffer)-1,0);
            if(n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }

        int Send(const std::string& message) override
        {
            return ::send(_sockfd,message.c_str(),message.size(),0);
        }

        void Close() override
        {
            if(_sockfd > 0)
                ::close(_sockfd);
        }

        int Connect(const std::string& server_ip,uint16_t port) override
        {
            InetAddr server(server_ip,port);
            return connect(_sockfd,server.NetAddrPtr(),server.NetAddrLen());
        }

    private:
        int _sockfd;//可以是listensockfd,也可以是sockfd
    };
}